<template>
  <base-table-layout
    title="员工管理"
    :total="total"
    :current-page="queryParams.pageNum"
    :page-size="queryParams.pageSize"
    @update:currentPage="val => queryParams.pageNum = val"
    @update:pageSize="val => queryParams.pageSize = val"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  >
    <!-- 搜索区域 -->
    <template #search>
      <el-input
        v-model="queryParams.employeeName"
        placeholder="员工姓名"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-input
        v-model="queryParams.phone"
        placeholder="手机号"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleSearch"
      />
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleSearch"
      >搜索</el-button>
      <el-button
        class="filter-item"
        type="info"
        icon="el-icon-refresh"
        @click="resetQuery"
      >重置</el-button>
    </template>

    <!-- 操作区域 -->
    <template #operation>
      <el-button
        type="success"
        icon="el-icon-plus"
        @click="handleAdd"
      >{{ showSelect ? '新增员工' : '新增' }}</el-button>
    </template>

    <!-- 表格区域 -->
    <template #table>
      <el-table
        v-loading="loading"
        :data="employeeList"
        border
        style="width: 100%"
        @row-click="handleRowClick"
      >
        <el-table-column label="员工ID" prop="employeeId" width="80" align="center" />
        <el-table-column label="姓名" prop="employeeName" align="center" />
        <el-table-column label="性别" align="center" width="80">
          <template slot-scope="scope">
            {{ scope.row.gender === 1 ? '男' : scope.row.gender === 2 ? '女' : '未知' }}
          </template>
        </el-table-column>
        <el-table-column label="职位" prop="position" align="center" />
        <el-table-column label="手机号" prop="phone" align="center" />
        <el-table-column label="邮箱" prop="email" align="center" />
        <el-table-column label="入职日期" prop="hireDate" align="center" width="180" />
        <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isActive === 1 ? 'success' : 'info'">
              {{ scope.row.isActive === 1 ? '在职' : '离职' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="180">
          <template slot-scope="scope">
            <template v-if="showSelect">
              <el-button 
                size="mini" 
                type="primary" 
                @click.stop="handleSelect(scope.row)"
              >选择</el-button>
            </template>
            <template v-else>
              <el-button size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <!-- 弹窗区域 -->
    <template #dialogs>
      <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="姓名" prop="employeeName">
            <el-input v-model="form.employeeName" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="form.gender">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker
              v-model="form.birthDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="入职日期" prop="hireDate">
            <el-date-picker
              v-model="form.hireDate"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>
          <el-form-item label="职位" prop="position">
            <el-input v-model="form.position" placeholder="请输入职位" />
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="form.phone" placeholder="请输入手机号" />
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="form.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="状态" prop="isActive">
            <el-radio-group v-model="form.isActive">
              <el-radio :label="1">在职</el-radio>
              <el-radio :label="0">离职</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </template>
  </base-table-layout>
</template>

<script>
import request from '@/utils/request'
import BaseTableLayout from '@/components/BaseTableLayout.vue'

export default {
  name: 'EmployeeManager',
  components: {
    BaseTableLayout
  },
  props: {
    showSelect: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: true,
      total: 0,
      employeeList: [],
      title: '',
      open: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        employeeName: undefined,
        phone: undefined,
        position: undefined,
        isActive: undefined,
        gender: undefined
      },
      form: {
        employeeId: undefined,
        employeeName: undefined,
        gender: 1,
        birthDate: undefined,
        hireDate: undefined,
        position: undefined,
        phone: undefined,
        email: undefined,
        isActive: 1
      },
      rules: {
        employeeName: [
          { required: true, message: '员工姓名不能为空', trigger: 'blur' }
        ],
        gender: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        hireDate: [
          { required: true, message: '请选择入职日期', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
        ],
        email: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        position: [
          { required: true, message: '请输入职位', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      try {
        this.loading = true
        const response = await request.get('/employees/page', {
          params: this.queryParams
        })
        this.employeeList = response.records
        this.total = response.total
      } catch (error) {
        console.error('获取员工列表失败:', error)
        this.$message.error('获取员工列表失败')
      } finally {
        this.loading = false
      }
    },

    handleSearch() {
      this.queryParams.pageNum = 1
      this.getList()
    },

    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        employeeName: undefined,
        phone: undefined,
        position: undefined,
        isActive: undefined,
        gender: undefined
      }
      this.getList()
    },

    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },

    handleCurrentChange(val) {
      this.queryParams.pageNum = val
      this.getList()
    },

    cancel() {
      this.open = false
      this.reset()
    },

    reset() {
      this.form = {
        employeeId: undefined,
        employeeName: undefined,
        gender: 1,
        birthDate: undefined,
        hireDate: undefined,
        position: undefined,
        phone: undefined,
        email: undefined,
        isActive: 1
      }
      this.$refs.form && this.$refs.form.resetFields()
    },

    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增员工'
    },

    async handleUpdate(row) {
      this.reset()
      try {
        const response = await request.get(`/employees/${row.employeeId}`)
        this.form = response
        this.open = true
        this.title = '修改员工'
      } catch (error) {
        console.error('获取员工详情失败:', error)
        this.$message.error('获取员工详情失败')
      }
    },

    async submitForm() {
      try {
        await this.$refs.form.validate()
        const formData = { ...this.form }
        if (formData.birthDate) {
          formData.birthDate = formData.birthDate.substring(0, 10)
        }
        if (formData.hireDate) {
          formData.hireDate = formData.hireDate.substring(0, 10)
        }

        let response
        if (this.form.employeeId) {
          // 修改
          response = await request.put('/employees', formData)
          this.$message.success('修改成功')
        } else {
          // 新增
          response = await request.post('/employees', formData)
          this.$message.success('新增成功')
          // 如果是选择模式，自动选择新添加的员工
          if (this.showSelect) {
            this.handleSelect(response)
          }
        }
        this.open = false
        this.getList()
      } catch (error) {
        console.error('保存失败:', error)
        this.$message.error('保存失败')
      }
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确认删除该员工吗？', '警告', {
          type: 'warning'
        })
        await request.delete(`/employees/${row.employeeId}`)
        this.$message.success('删除成功')
        this.getList()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          this.$message.error('删除失败')
        }
      }
    },

    handleRowClick(row) {
      if (this.showSelect) {
        this.handleSelect(row)
      }
    },

    handleSelect(row) {
      if (!row.userId) {
        this.$emit('select', row)
      } else {
        this.$message.warning('该员工已绑定账号')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}
</style>
